import { Component, OnInit ,Output,EventEmitter} from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { forEach } from '@angular/router/src/utils/collection';
import { InterceptorService } from '../../../../share/interceptor.service';
import { Router } from '@angular/router';
import { NoticeEntity } from '../../../../models/notice-entity';
import { NoticeBrowseModel } from '../../../../models/NoticeBrowseModel';
import { PeriodPersonModel } from '../../../../models/PeriodPersonModel';
import { PersonalInfoEntity } from '../../../../models/personal-info-entity';
//弹框
import {ConfirmationService} from 'primeng/primeng';//删除确认弹框-cyl
import 'ztree';
import { timeInterval } from 'rxjs/operators/timeInterval';

@Component({
  selector: 'app-add-notice',
  templateUrl: './add-notice.component.html',
  //templateUrl: './test.html',
  styleUrls: ['./add-notice.component.css'],
})
export class AddNoticeComponent implements OnInit {


  @Output() cancleComponent = new EventEmitter();   //定义装饰器

  private noticeEntity:NoticeEntity=new NoticeEntity();
  
  constructor(private http:InterceptorService,private router:Router,private confirmationService: ConfirmationService) {}

  ngOnInit() {
    this.getCategory();
    this.getPerson();
  }

  notifyTypeId; //选择的通知类型Id
  notifyTypeOptions:any[]=[];//通知类型选项

  //获取通知分类信息
  getCategory(){
    // 后端返回 data 结构：
    // {
    //   "id": "0044fbbe28c254673bc37a",
    //   "operator": "hao",
    //   "isDelete": 0,
    //   "remark": "13",
    //   "createTime": "2017-11-26 02:48:40",
    //   "updateTime": "2018-01-09 06:11:01",
    //   "columnName": "数据结构",
    //   "operatorId": "操作人id",
    //   "timestampTime": 1515478555000
    // }

    let url="graduate-web/noticeCategory/selectNoticeCategoryInfo/";
    this.http.get(url).subscribe(res=>{
      if(res ==undefined){
        console.log("查询通知分类无返回结果")
      }else{
        if(res.json().code=='0000'){
          this.notifyTypeOptions = res.json().data;
          console.log(this.notifyTypeOptions)
        }else{
          console.log(res.json().message)
        }
      }
    })

  }

  zNodes:any[];
  setting = {
    data: {
      simpleData: {
        enable: true
      }
    },
    check: {
        enable: true
    }
  };
  personIds:any[]=[];
  periodPersonModels:PeriodPersonModel[]=[];
  //获取接收人信息
  getPerson(){
    let url = 'graduate-web/browse/findPeriodPersonModels/';
    this.http.get(url).subscribe(res=>{
      if(res ==undefined){
        console.log("查询接收人信息无返回结果")
      }else{
        if(res.json().code=='0000'){
          this.periodPersonModels=res.json().data;
          this.setPersonOptions();
        }else{
          console.log(res.json().message);
          this.showDialog(res.json().message+"\n请尝试刷新！");
        }
      }
    })
  }

  //设置人员树形结构
  setPersonOptions(){
    let nodes:any[]=[];
    nodes.push({id:0,name:'全部联系人'});
    this.periodPersonModels.forEach(periodPersonModel=>{
      nodes.push({id:periodPersonModel.periodId,pId:0,name:periodPersonModel.periodName});
      if(periodPersonModel.personalInfoList!=null){
        //接收人员信息
        let personalInfoEntitys:PersonalInfoEntity[]=periodPersonModel.personalInfoList;
        personalInfoEntitys.forEach(person=>{
          nodes.push({id:person.id,pId:periodPersonModel.periodId,name:person.name})
        })
      }
    })
    this.zNodes=nodes;
    //生成属性结构
    $.fn.zTree.init($("#ztree"),this.setting,this.zNodes);
  }

  notifyInfo:any;//通知内容
  notifyTitle:any;//通知标题

  //添加通知信息
  addNotify(){
    //验证数据内容

    //获取分类数据
    console.log(this.notifyTypeId);
    if(this.notifyTypeId ==undefined){
      console.log("请选择通知类别");
      this.showDialog("请选择通知类别");
      return;
    }
    this.noticeEntity.columnId=this.notifyTypeId;
    
    //获取接收人数据
    var treeObj =$.fn.zTree.getZTreeObj("ztree");
    var nodes = treeObj.getCheckedNodes();
    let browsePersons:NoticeBrowseModel[]=[];
    for(let i=0;i<nodes.length;i++){
      if (!nodes[i].isParent) {
        let browsePerson:NoticeBrowseModel=new NoticeBrowseModel();
        browsePerson.browsePersonId=nodes[i].id;
        browsePersons.push(browsePerson);
      } 
    }
    if(browsePersons.length==0){
      console.log("请选择接收人");
      this.showDialog("请选择接收人");
      return;
    }
    this.noticeEntity.browsePersons=browsePersons;

    //获取通知标题
    //获取通知内容
    if(this.notifyTitle==undefined){
      console.log("请输入通知标题");
      this.showDialog("请输入通知标题");
      return;
    }
    this.noticeEntity.title = this.notifyTitle;

    //获取通知内容
    if(this.notifyInfo==undefined){
      console.log("请输入通知内容");
      this.showDialog("请输入通知内容");
      return;
    }
    this.noticeEntity.noticeContent=this.notifyInfo;

    //补充其他数据
    this.noticeEntity.operator=localStorage.getItem('userName')==undefined?"大米时代":"大米时代";//操作人名称
    this.noticeEntity.operatorId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//操作人Id
    this.noticeEntity.publisherId=localStorage.getItem('userId')==undefined?"bjdmsd":this.noticeEntity.publisherId=localStorage.getItem('userId');//创建人ID
    
    //提交到服务器
    let url="graduate-web/notice/addNotice/";
    let body=JSON.stringify(this.noticeEntity);
    this.http.post(url,body).subscribe(res=>{
      if(res ==undefined){
        console.log("查询通知分类无返回结果")
      }else {
        console.log(res.json().message);
        
        this.showDialog(res.json().message);
        //todo 如何延时触发跳转  
        if(res.json().code=='0000'){
          //返回上一页
          this.router.navigateByUrl('workspace/notice/my-notice');
        }
      }
    })
    alert("添加成功");
    this.cancleComponent.emit("cancle");  //添加成功，页面跳转回原list页面
  }
  //取消添加
  cancelClick(){
    //清除数据
    this.personIds=[];
    this.notifyTypeId=undefined;
    this.notifyInfo=undefined;
    this.cancleComponent.emit("cancle"); //点击取消，页面跳转回原list页面
    //返回上一页
    // this.router.navigateByUrl('workspace/notice/my-notice');
  }

  //**********************************************提示框Start**************************************88 */
  display:boolean=false;
  messages:"";
  /**
   * 提示框
   */
  showDialog(string){
    this.messages=string;
    this.display=true;
  }
  //**********************************************提示框END**************************************88 */



  text1: string = '<div>Hello World!</div><div>PrimeNG <b>Editor</b> Rocks</div><div><br></div>';
    
  text2: string;
}
